package com.mingtu.dzpatrol.decoration;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import static com.blankj.utilcode.util.SizeUtils.dp2px;

/**
 * @ClassName :
 * @Author : wkk
 * @Date : 2020/7/16 15:18:08
 * @Email : 1281573890@qq.com
 * @Eescription : 设置列表的上下距离
 */
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private int left;
    private int right;
    private int top;
    private int bottom;
    private int middle;

    public SpacesItemDecoration(int left, int right, int top, int bottom, int middle) {
        this.left = dp2px(left);
        this.right = dp2px(right);
        this.top = dp2px(top);
        this.bottom = dp2px(bottom);
        this.middle = dp2px(middle);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view,
                               RecyclerView parent, RecyclerView.State state) {
        LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
        if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {
            //竖直方向的
            //最后一项需要 bottom
            if (layoutManager.getItemCount() == 1) {
                outRect.top = top;
                outRect.bottom = bottom;
            } else if (layoutManager.getItemCount() == 2) {
                if (parent.getChildAdapterPosition(view) == 0) {
                    outRect.top = top;
                    outRect.bottom = bottom;
                } else {
                    outRect.bottom = bottom;
                }
            } else {
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.bottom = bottom;
                } else if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 2) {
                    outRect.bottom = middle;
                    outRect.top = middle;
                } else if (parent.getChildAdapterPosition(view) == 0) {
                    outRect.top = top;
                } else {
                    outRect.top = middle;
                }
            }


        } else {
            //水平方向的
            //最后一项需要right
            if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                outRect.right = right;
            } else if (parent.getChildAdapterPosition(view) == 0) {
                outRect.left = left;
            } else {
                outRect.left = middle;
            }
        }
    }
}
